package com.hualan.controller;

import com.github.pagehelper.PageInfo;
import com.hualan.pojo.Result;
import com.hualan.pojo.SysUser;
import com.hualan.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RestController
@RequestMapping("/sysUser")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;


    @GetMapping("/list")
    public Result getUserList(SysUser sysUser,
                              @RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "5") int pageSize) {
        PageInfo<SysUser> pageInfo = sysUserService.getUserList(sysUser, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    @PostMapping("/add")
    public Result addUser(@RequestBody SysUser sysUser) {
        int result = sysUserService.addUser(sysUser);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("添加用户失败");
        }
    }

    @PostMapping(value = "/login", consumes = "application/json")
    public Result login(@RequestBody SysUser sysUser) {
        try {
            if (StringUtils.isEmpty(sysUser.getPhone()) || StringUtils.isEmpty(sysUser.getPassword())) {
                return Result.error("手机号和密码不能为空");
            }
            SysUser user = sysUserService.login(sysUser.getPhone(), sysUser.getPassword());
            if (user != null) {
                // 移除密码等敏感信息
                user.setPassword(null);
                return Result.success(user);
            } else {
                return Result.error("手机号或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统繁忙，请稍后再试");
        }
    }
    @PutMapping ("/update")
    public Result updateUser(@RequestBody SysUser sysUser) {
        int result = sysUserService.updateUser(sysUser);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("更新用户失败");
        }
    }
    @DeleteMapping("/delete/{id}")
    public Result deleteUserById(@PathVariable Integer id) {
        int result = sysUserService.deleteUserById(id);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("删除用户失败");
        }
    }

    @DeleteMapping("/delete/batch")
    public Result deleteUsersByIds(@RequestBody List<Integer> ids) {
        System.out.println(123);
        int result = sysUserService.deleteUsersByIds(ids);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("批量删除用户失败");
        }
    }
}
